package spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.TaskItemAllotTask;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.executor.task.TaskExecutorOnlineTaskItemAllotTask;
import spring.cloud.tasks.tasks_manager.tasks_manager.task_item_allot.task.TaskItem;

import java.util.Iterator;
import java.util.List;

/**
 * 恢复executor流量，标记该executor的noTraffic为false，平衡摘取分片
 */
@Slf4j
@Setter
@Getter
public class ExecutorRecoverTrafficTaskItemAllotTask extends TaskItemAllotTask {

    private String executorId;

    public ExecutorRecoverTrafficTaskItemAllotTask(AllotTaskItemService allotTaskItemService, String executorId) {
        super(allotTaskItemService);
        this.executorId = executorId;
    }

    @Override
    protected void logStartInfo() {
        log.info("Execute the {} with {} recover traffic", this.getClass().getSimpleName(), executorId);
    }

    @Override
    protected boolean pick(List<String> taskIdList,//
                           List<String> enableTaskIdList,//
                           List<TaskItem> taskItemList,//
                           List<Executor> onlineExecutorList,//
                           List<Executor> onlineOwnTrafficExecutorList) throws Exception {
        // 设置该executor的noTraffic为false
        Executor targetExecutor = null;
        Iterator<Executor> iterator = onlineExecutorList.iterator();
        while (iterator.hasNext()) {
            Executor executor = iterator.next();
            if (executor.getExecutorId().equals(executorId)) {
                executor.setLostTraffic(false);
                onlineOwnTrafficExecutorList.add(executor);
                targetExecutor = executor;
                break;
            }
        }
        if (targetExecutor == null) {
            log.warn("The executor {} maybe offline, unnecessary to recover traffic", executorId);
            return false;
        }

        // 平衡摘取每个作业能够运行的分片，可以视为taskIdList中每个作业的task executor online
        //这段的代码是串行执行
        for (String taskId : targetExecutor.getTaskIdList()) {
            new TaskExecutorOnlineTaskItemAllotTask(allotTaskItemService, executorId, taskId).pickIntelligent(enableTaskIdList, taskItemList, onlineOwnTrafficExecutorList);
        }
        return true;
    }
}
